import { reqUserLogin, reqUserRegister, reqGetUserInfo } from "../../api";
import { req, API_AUTH_FANSNUM, API_AUTH_FOLLOWSNUM } from '@/api/api'

const state = {
  token: localStorage.getItem('TOKEN') || '',
  userInfo: localStorage.getItem('music-userInfo') ? JSON.parse(localStorage.getItem('music-userInfo')) : { name: '未登录' }
};
const mutations = {
  USERLOGIN (state, token) {
    state.token = token
  },
  SET_USERINFO (state, userInfo) {
    state.userInfo = userInfo
  }
};
const actions = {
  //登录
  async UserLogin ({ commit }, user) {
    let result = await reqUserLogin(user);
    // console.log(result);
    if (result.code == 200) {
      commit('USERLOGIN', result.token);
      localStorage.setItem("TOKEN", result.token)
      reqGetUserInfo({ token: result.token }).then(async res => {
        const { id } = res.object
        res.object.evens = 0
        res.object.avatar = 'http://p1.music.126.net/cwgdy8pRLlrd4dy1Hi2W0Q==/19164487672742385.jpg?param=140y140'
        const res1 = await req.list(API_AUTH_FANSNUM, { id })
        const res2 = await req.list(API_AUTH_FOLLOWSNUM, { id })
        res.object.fans = res1.total
        res.object.follows = res2.total
        commit('SET_USERINFO', res.object);
        localStorage.setItem("music-userInfo", JSON.stringify(res.object))
      })
      return Promise.resolve(result)
    } else {
      return Promise.reject(new Error('faile'))
    }
  },

  //注册
  async userRegister ({ commit }, user) {
    let result = await reqUserRegister(user);
    if (result.code == 200) {
      return 'ok'
    } else {
      return Promise.reject(new Error('faile'))
    }
  },

};


const getters = {};

export default {
  state,
  mutations,
  actions,
  getters,
}
